/* eslint-disable no-param-reassign */
import moment from 'moment';
import { cloneDeep, pick } from 'lodash';

const transformBasicConfDataToSubmit = (data:any) => {
  const currentData = cloneDeep(data);
  currentData.pipelineScheduleList.forEach((item:any) => {
    if (item.timeRange) {
      item.startHourOfDay = moment(item.timeRange.start).format('h');
      item.endHourOfDay = moment(item.timeRange.end).format('h');
      delete item.timeRange;
    }
    if (item.executeTime) {
      item.executeTime = moment(item.executeTime).format('HH:mm');
    }
  });
  return currentData;
};

const transformBasicConfDataToUse = (data:any) => {
  let currentData = cloneDeep(data);
  currentData = pick(currentData, ['appVersionTriggerEnable', 'id', 'name', 'pipelineScheduleList', 'token']);

  if (!currentData.pipelineScheduleList) {
    currentData.pipelineScheduleList = [];
  }

  currentData.pipelineScheduleList.forEach((item:any) => {
    if (item.startHourOfDay && item.endHourOfDay) {
      item.timeRange = {
        start: moment().set('hour', item.startHourOfDay),
        end: moment().set('hour', item.endHourOfDay),
      };
    }
    if (item.executeTime) {
      const currentTime = moment();
      currentTime.set('hour', item.executeTime.split(':')[0]);
      currentTime.set('minute', item.executeTime.split(':')[1]);
      item.executeTime = currentTime;
    }
  });

  return currentData;
};

const validateBasicConfigurationData = (data:any) => {
  if (!data.name) {
    return '请填写基础配置信息';
  }
  return '';
};

const validateStageData = (data:any) => {
  if (!data.length) {
    return '请添加步骤';
  }
  let taskNum = 0;
  data.forEach((item:any) => {
    taskNum += item.jobList.length;
  });

  if (taskNum === 0) {
    return '请添加任务';
  }

  const validateNotPass = data.some(
    (stage:any) => stage.jobList.some((task:any) => task.completed === false),
  );

  if (validateNotPass) {
    return '存在错误阶段';
  }

  return '';
};

export {
  transformBasicConfDataToSubmit,
  transformBasicConfDataToUse,
  validateBasicConfigurationData,
  validateStageData,
};
